//
//  MainVCViewModel.swift
//  mmda
//
//  Created by 李陆涛 on 2018/4/19.
//  Copyright © 2018年 mmda. All rights reserved.
//

//import CoreLocation


/// 显示类型
///
/// - blog: 动态
/// - user: 用户
enum ShowType {
    
    case blog
    case user
}

class MainVCViewModel {
    
    var refreshStatusDidChange: ((Bool) -> Void)?
    var removeMapData: (() -> Void)?
    var addMapData: ((Array<Annotation>) -> Void)?
    
    
    private var dataSource:[Any] = [Any]()
    private var _lastLoc:CLLocationCoordinate2D?
    private var _showType:ShowType = .blog
    
    var lastLoc:CLLocationCoordinate2D? {
        
        set {
            
            guard let loc = newValue else { return }
            
            
            if let lastloc = lastLoc {
                
                
                let point1 = BMKMapPointForCoordinate(loc)
                let point2 = BMKMapPointForCoordinate(lastloc)
                
                
                let distance = BMKMetersBetweenMapPoints(point1, point2)
                
                if distance < 1000 {
                    return
                }
            }
            forceReload(loc)
        }
        
        get {
            
            return _lastLoc
        }
        
    }
    
    var showType: ShowType! {
        
        set {
            if _showType != newValue {
                
                _showType = newValue
                dataSource.removeAll()
                removeMapData?()
                forceReload(self.lastLoc)
            }
        }
        
        get {
            
            return _showType
        }
        
    }
    
    /// 强制刷新
    ///
    /// - Parameter location: 位置
    func forceReload(_ location: CLLocationCoordinate2D?) {
        
        guard let loc = location else { return }
        
        _lastLoc = loc
        
        DispatchQueue.main.async {
            [weak self] in
            guard let `self` = self else { return }
            self.refreshStatusDidChange?(true)
        }
        reloadData()
    }
    
    private func reloadData() {
        
        guard let loc = _lastLoc else {
            
            DispatchQueue.main.async {
                [weak self] in
                guard let `self` = self else { return }
                self.refreshStatusDidChange?(false)
            }
            
            return
        }
        
        switch _showType {
            
        case .blog:
            getBlogs(loc: loc)
        case .user:
            getUsers(loc: loc)
        }
    }
    

    /// 获取定位周围的blog
    ///
    /// - Parameter loc: 定位
    private func getBlogs(loc:CLLocationCoordinate2D) {
        
        NetAPI.blog(loc:loc).request([Blog].self) {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            self.refreshStatusDidChange?(false)
            
            guard let array = response as? [Blog] else {
                
                return
            }
            
            DispatchQueue.global().async {
                [weak self] in
                guard let `self` = self else { return }
                var annArray = [Annotation]()
                
                for blog in array {
                    
                    if self.dataSource.contains(where: { other -> Bool in
                        
                        guard let other = other as? Blog else {return false}
                        
                        return other._id == blog._id
                    }) {
                        continue
                    }
                    
                    self.dataSource.append(blog)
                    
                    guard let lat = blog.latitude,let lng = blog.longitude else { continue }
                    
                    let loc = CLLocationCoordinate2DMake(lat, lng)
                    
                    let ann = Annotation(coordinate: loc)
                    ann.model = blog
                    annArray.append(ann)
                }
                
                DispatchQueue.main.async {
                    if self.showType != .blog { return}
                    
                    self.addMapData?(annArray)
                }
            }
        }
    }
    /// 获取定位周围的user
    ///
    /// - Parameter loc: 定位
    private func getUsers(loc:CLLocationCoordinate2D) {
        
        NetAPI.user(loc: loc).request([User].self) {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            self.refreshStatusDidChange?(false)
            guard let array = response as? [User] else { return }
            
            DispatchQueue.global().async {
                [weak self] in
                guard let `self` = self else { return }
                var annArray = [Annotation]()
                
                for user in array {
                    
                    if self.dataSource.contains(where: { other -> Bool in
                        
                        guard let other = other as? User else {return false}
                        
                        return other._id == user._id
                    }) {
                        continue
                    }
                    
                    self.dataSource.append(user)
                    
                    guard let lat = user.latitude,let lng = user.longitude else { continue }
                    
                    let loc = CLLocationCoordinate2DMake(lat, lng)
                    
                    let ann = Annotation(coordinate: loc)
                    ann.model = user
                    annArray.append(ann)
                }
                
                DispatchQueue.main.async {
                    
                    if self.showType != .user { return}
                    self.addMapData?(annArray)
                }
            }
            
        }
    }
}




